<?php
//定义常量
//图片的http前缀
define('SERVER_URL','http://' . $_SERVER['SERVER_ADDR'].__ROOT__ );
//文件保存的路径前缀
define('FILE_ADD',"/opt/lampp/htdocs/xampp/shuangyue");
/**
 * 验证密码长度不能小于6位。
 * @return boolean
 *
 *
 */
function checkPwd()
{
    $password = $_POST['pwd'];

    if(strlen($password)>=6){
        return true;
    }else{
        return false;
    }

}


function check_verify($code, $id = '')
{
    $verify = new \Think\Verify();
    return $verify->check($code, $id);
}



function content_category_list()
{
    $list = M('ContentCategory')
        ->field(array(
            'id',
            'name',
            'path',
            'concat(path,",",id)'=>'bpath',
            'sort',
        ))
        ->where('status =1')
        ->order('bpath,sort')
        ->select();

    foreach($list as $k =>$val){
        $number = count(explode(',',$val['path']));

        if($number>1){
            $str = '┊';
            for($i=1;$i<$number;$i++){
                $str .='〓';
            }
            //$str .='┣━━ ';
            $list[$k]['newname'] = $str.$val['name'];
        }else{
            $list[$k]['newname'] = $val['name'];
        }

    }
    return $list;
}

if( ! function_exists('array_column'))
{
    function array_column($input, $columnKey, $indexKey = NULL)
    {
        $columnKeyIsNumber = (is_numeric($columnKey)) ? TRUE : FALSE;
        $indexKeyIsNull = (is_null($indexKey)) ? TRUE : FALSE;
        $indexKeyIsNumber = (is_numeric($indexKey)) ? TRUE : FALSE;
        $result = array();

        foreach ((array)$input AS $key => $row)
        {
            if ($columnKeyIsNumber)
            {
                $tmp = array_slice($row, $columnKey, 1);
                $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : NULL;
            }
            else
            {
                $tmp = isset($row[$columnKey]) ? $row[$columnKey] : NULL;
            }
            if ( ! $indexKeyIsNull)
            {
                if ($indexKeyIsNumber)
                {
                    $key = array_slice($row, $indexKey, 1);
                    $key = (is_array($key) && ! empty($key)) ? current($key) : NULL;
                    $key = is_null($key) ? 0 : $key;
                }
                else
                {
                    $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
                }
            }

            $result[$key] = $tmp;
        }

        return $result;
    }
}

/**
 * 得到系统配置信息
 * @param string $conf_name
 * @return NULL|mixed
 */
function get_system_conf($conf_name) {
	if (!$conf_name) {
		return null;
	}

	$dSysConf = D('SysConf');


	$data =  $dSysConf->getSysConfByName($conf_name);

	if ($data['conf_value']) return $data['conf_value'];
	return null;

}

//获取客户端IP地址
function getClientIp() {
	if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
		$ip = getenv("HTTP_CLIENT_IP");
	else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
		$ip = getenv("HTTP_X_FORWARDED_FOR");
	else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
		$ip = getenv("REMOTE_ADDR");
	else if (isset($_SERVER ['REMOTE_ADDR']) && $_SERVER ['REMOTE_ADDR'] && strcasecmp($_SERVER ['REMOTE_ADDR'], "unknown"))
		$ip = $_SERVER ['REMOTE_ADDR'];
	else
		$ip = "unknown";
	return ($ip);
}

function getShowTime($create_time, $format = NULL) {
	/*
	 10秒前
	 X≤10秒
	 30秒前
	 10＜X≤60秒时，个位秒数四舍五入显示整十位，如X=56秒时显示，格式：60秒前。
	 12分钟前
	 1分＜X≤60分00秒时，十位秒数四舍五入显示整分钟数，如X=3分56秒时显示，格式：4分钟前。
	 今天13:45
	 X>60分00且发布时间和当前时间在同一天时，舍弃秒数显示，如X=2小时11分12秒时显示，格式：今天13:45。
	 11月22日 12:13
	 X>60分00且发布时间和当前时间在不同一天但在同一年时，显示月日时分，格式：11月22日 12:13。
	 2010-12-31 12:44
	 发布时间和当前时间在不在同一年时，显示年月日时分，格式：2010-12-31 12:44。

	 */
	$time = time();
	$span_time = $time - $create_time;
	$day = date('d', $create_time) - date('d', $time);
	$year = date('Y', $create_time) - date('Y', $time);
	if ($span_time < 10)
		return '10秒前';
	if ($span_time < 30)
		return '30秒前';
	if ($span_time < 60)
		return ceil($span_time / 10) . '0秒前';
	if ($span_time < 3600)
		return ceil($span_time / 60) . '分钟前';
	if ($day == 0 && $year == 0)
		return '今天' . date('H:i', $create_time);

	if ($format) {
		return date($format, $create_time);
	}
	if ($year == 0)
		return date('m月d日', $create_time);

	return date('Y-m-d', $create_time);
}

//截取字符串
function cut_str($string, $sublen, $showEllipsis=false, $start = 0, $code = 'UTF-8') {
	if ($code == 'UTF-8') {
		$pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
		preg_match_all($pa, $string, $t_string);
		$tempStr = $string;
		$countLen = $sublen * 2; //50
		$iCharCount = 0;
		$iWordCount = 0;
		foreach ($t_string [0] as $string_val) {
			if ($iCharCount + $iWordCount * 2 >= $countLen)
				break;
				if (Ord($string_val[0]) < 128 && Ord($string_val[0]) > 31) {
					$iCharCount++;
				}
				else {
					if ($iCharCount + ($iWordCount + 1) * 2 > $countLen)
						break;
						$iWordCount++;
				}
		}
		//英文字符算1个字节，中文字符算2个字节。
		$sublen = $iCharCount + $iWordCount; //
		if (count($t_string [0]) - $start > $sublen) {

			$tempStr = join('', array_slice($t_string [0], $start, $sublen));
			if ($showEllipsis)
				$tempStr .= '...';
		} else {
			$tempStr = join('', array_slice($t_string [0], $start, $sublen));
		}
		return $tempStr;
	}
	else {
		$start = $start * 2;
		$sublen = $sublen * 2;
		$strlen = strlen($string);
		$tmpstr = '';

		for ($i = 0; $i < $strlen; $i++) {
			if ($i >= $start && $i < ($start + $sublen)) {
				if (ord(substr($string, $i, 1)) > 129) {
					$tmpstr .= substr($string, $i, 2);
				}
				else {
					$tmpstr .= substr($string, $i, 1);
				}
			}
			if (ord(substr($string, $i, 1)) > 129)
				$i++;
		}
		if (strlen($tmpstr) < $strlen && $showEllipsis) {
			$tmpstr .= "...";
		}
		return $tmpstr;
	}
}


/**
 * 取得浏览类型
 */
function getBrowser() {

	if (stripos($_SERVER["HTTP_USER_AGENT"], "Iphone") || stripos($_SERVER["HTTP_USER_AGENT"], "Ipad")) {
		$browser = 'ios';
	}
	elseif (stripos($_SERVER["HTTP_USER_AGENT"], "Android")) {
		$browser = 'android';
	}
	elseif (strpos($_SERVER["HTTP_USER_AGENT"], "TheWorld") || strpos($_SERVER["HTTP_USER_AGENT"], "QIHU THEWORLD")) {
		$browser = 'world';
	}
	elseif (strpos($_SERVER["HTTP_USER_AGENT"], "Maxthon")) {
		$browser = 'aoyou';
	}
	elseif (strpos($_SERVER["HTTP_USER_AGENT"], "TencentTraveler")) {
		$browser = 'telcent';
	}
	elseif (strpos($_SERVER["HTTP_USER_AGENT"], "SE 2") AND strpos($_SERVER["HTTP_USER_AGENT"], "MetaSr")) {
		$browser = 'sogou';
	}
	elseif (strpos($_SERVER["HTTP_USER_AGENT"], "360SE") AND !strpos($_SERVER["HTTP_USER_AGENT"], "TencentTraveler")) {
		$browser = 'qihu';
	}
	elseif (strpos($_SERVER["HTTP_USER_AGENT"], "QIHU 360EE") AND !strpos($_SERVER["HTTP_USER_AGENT"], "TencentTraveler")) {
		$browser = 'qihu';
	}
	elseif (strpos($_SERVER["HTTP_USER_AGENT"], "MSIE 9.0")) {
		$browser = 'ie9';
	}
	elseif (strpos($_SERVER["HTTP_USER_AGENT"], "MSIE 8.0")) {
		$browser = 'ie8';
	}
	elseif (strpos($_SERVER["HTTP_USER_AGENT"], "MSIE 7.0")) {
		$browser = 'ie7';
	}
	elseif (strpos($_SERVER["HTTP_USER_AGENT"], "MSIE 6.0")) {
		$browser = 'ie6';
	}
	elseif (strpos($_SERVER["HTTP_USER_AGENT"], "Firefox")) {
		$browser = 'firefox';
	}
	elseif (strpos($_SERVER["HTTP_USER_AGENT"], "Chrome")) {
		$browser = 'chrome';
	}
	elseif (strpos($_SERVER["HTTP_USER_AGENT"], "Safari")) {
		$browser = 'safari';
	}
	else {
		$browser = $_SERVER["HTTP_USER_AGENT"];
	}
	return $browser;
}

//判断浏览器是不是微信
function isWeixin(){
	return preg_match('/(MicroMessenger)/i', $_SERVER["HTTP_USER_AGENT"]);
}

//判断是否是移动端访问
function isMobile(){
	return preg_match('/(iphone|ipod|android|mobile|samsung|BlackBerry|webOS|Windows Phone)/i', $_SERVER["HTTP_USER_AGENT"]);
}


//判断是否APP访问
function isZmbb(){
	return preg_match('/(ID:)/i', $_SERVER["HTTP_USER_AGENT"]);
}


/**
 * 获取格式化日期和星期
 *
 * @param string $date 日期
 * @return string
 */
function get_date_week($date) {
	if (!$date) {
		return '';
	}

	$formatDate = date('m/d', strtotime($date));

	$week = array('星期日','星期一','星期二','星期三','星期四','星期五','星期六');

	return $formatDate . ' ' . $week[date('w', strtotime($date))];
}

/**
 * 获取随机字符串
 *
 * @param int $len 随机字符串长度
 * @param string $chars 随机字符串可以包含的字符
 * @return string
 */
function get_rand_string($len = 6, $chars = '123456789') {
	$_chars = str_shuffle(str_repeat($chars, $len));
	return substr($_chars, 0, $len);
}


/**
 * 获取手机运营商
 *
 * @param int $sMobile
 *
 * @return string
 */
function getMobileType($sMobile) {
	$chinaMobile = array(134, 135, 136, 137, 138, 139, 150, 151, 152, 157, 158, 159, 147, 182, 183, 184, 187, 188,178);
	$chindUnionCom = array(130, 131, 132, 145, 155, 156, 185, 186,176);
	$chinaTelCome = array(133, 153, 180, 181, 189,177);
	$vietual = array(170);
	$prefix = substr($sMobile, 0, 3);
	if (in_array($prefix, $chinaMobile)) {
		return  '中国移动';
	}

	if (in_array($prefix, $chindUnionCom)) {
		return  '中国联通';
	}

	if (in_array($prefix, $chinaTelCome)) {
		return '中国电信';
	}

	if (in_array($prefix, $vietual))  {
		return '虚拟运营商';
	}
	return '未知';
}

/**
 * 给密码进行分级
 * @param string $pw
 * @return boolean
 */
function passwd_grade($pw) {
	$grade = 0;
	if (strlen($pw) >= 8) {
		//全数字 || 全英文
		if (strlen(preg_replace("/^(.)\\1+$/", "", $pw)) == 0) {
			$grade = 1;
		}
		else if (preg_match("/^\d*$/", $pw) || preg_match("/^[a-z]*$/i", $pw)) {
			$grade = 1;
		}
		else if (preg_match("/^[a-z\d]*$/i", $pw)) {
			$grade = 2;
		}
		else {
			$grade = 3;
		}
	}
	return $grade;
}

/**
 *将parse_url分解的数组重新拼装成url
 */
function build_url($urlArr) {
	$url =  (empty($urlArr['scheme']) ? '' : $urlArr['scheme']) .
	(empty($urlArr['host']) ? '' : '://' . $urlArr['host']) .
	$urlArr['path'] .
	(empty($urlArr['query']) ? '' : '?' . $urlArr['query']) .
	(empty($urlArr['fragment']) ? '' : '#' . $urlArr['fragment']);
	return $url;
}




function getRandomHeader() {
	$flag = mt_rand(0,6);
	$headerlibs = C('AVATAR_LIB');
	return $headerlibs[$flag];
}



function getcdn() {
	$flag = mt_rand(0,3);
	if (!$flag) {
		$flag='';
	}
	return 'http://static' . $flag . '.51dy.ren';
}


/**
 * @desc 压缩上传的图片
 * * @param string $imgUrl 上传的图片的网络路径
 * * @param string $filePath 上传图片在服务器上的物理物价
 * * @param string $width  压缩成宽度  默认为 200
 * * @param string $height  压缩成高度 默认为 200
 * * @param string $type  压缩成图片的类型 见thinklphp 的压缩类型
 */

function thumbnails($imgUrl=null,$filePath=null,$width=200, $height=200, $type=\Think\Image::IMAGE_THUMB_FILLED)
{
	if($imgUrl && $filePath) {
		$image = new \Think\Image();
		$image->open($filePath);
		//缩略图路径和文件名
		$shortStaticURL = substr($filePath,0,strrpos($filePath,'.'));
		//缩略图后缀
		$exe = substr($filePath,strrpos($filePath,'.'));
		$logoPath = $shortStaticURL.'_thumb_'.$width.'x'.$height.$exe;
		//缩放后填充
		$image->thumb($width, $height,$type)->save($logoPath);
		$newUrl =dirname($imgUrl).'/'.basename($logoPath);
		return $newUrl;
	}else{
		return null;
	}

}

